<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use GuzzleHttp\Client;

class WeChatController extends Controller
{

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $app = app('wechat.official_account');
        $app->server->push(function($message){
            return "欢迎关注！";
        });

        return $app->server->serve();
    }

    public function login(Request $request)
    {
        $code = $request->input('code');
        $config = [
                'app_id' => getenv('WECHAT_MINI_PROGRAM_APPID'),
                'secret' => getenv('WECHAT_MINI_PROGRAM_SECRET'),
                'grant_type' => 'authorization_code',
        ];

        $app = Factory::miniProgram($config);

        $guzzle = new Client();

        $response = $guzzle->post(getenv('APP_URL').'/oauth/token', [
                'form_params' => [
                        'grant_type' => 'client_credentials',
                        'client_id' => getenv('CLIENT_ID'),
                        'client_secret' => getenv('CLIENT_SECRET'),
                ],
        ]);
        $access_token = json_decode((string) $response->getBody(), true)['token_type'] . ' ' . json_decode((string) $response->getBody(), true)['access_token'];
        $secret = $app->auth->session($code);
        session([ $access_token => $secret['session_key'] . ' ' . $secret['openid']]);
        dd(session()->all());
        return $access_token;
//        session(['key' => 'value']);
    }

    public function checkSignature(Request $request)
    {
        $signature = $request->input('signature');
        $timestamp = $request->input('timestamp');
        $nonce = $request->input('nonce');

        $token = 'WeChat';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if($tmpStr == $signature){
            return $tmpStr;
        }else{
            return '';
        }
    }

    public function user()
    {
        $user = session(''); // 拿到授权用户资料

        dd($user);
    }
}